package com.example.keli.ui.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.keli.R;
import com.example.keli.api.HttpUtils;
import com.example.keli.api.RetrofitManager;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.BaseFragment;
import com.example.keli.base.app.C;
import com.example.keli.base.utils.GlideUtil;
import com.example.keli.base.utils.ToastUtil;
import com.example.keli.ui.home.activity.ObjectDetailActivity;
import com.example.keli.ui.my.adapter.GridAdapter;
import com.example.keli.ui.my.adapter.MyActiveAdapter;
import com.example.keli.ui.my.bindinfo.SafeInfoActivity;
import com.example.keli.ui.my.commission.CommissionActivity;
import com.example.keli.ui.my.commission.CommissionTypeActivity;
import com.example.keli.ui.my.invite.InviteActivity;
import com.example.keli.ui.my.love.LoveActivity;
import com.example.keli.ui.my.model.Extract;
import com.example.keli.ui.my.model.MyGridModel;
import com.example.keli.ui.my.model.UserInfo;
import com.example.keli.ui.my.star.StarActivity;
import com.example.keli.ui.my.vote.VoteActivity;
import com.example.keli.ui.userinfo.PersonDataActivity;
import com.example.keli.ui.userinfo.SettingActivity;
import com.flyco.roundview.RoundTextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * description $desc$
 * created by jerry on 2019/3/18.
 */
public class MyFragment extends BaseFragment {

    @BindView(R.id.iv_set)
    ImageView ivSet;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_nick)
    TextView tvNick;
    @BindView(R.id.tv_des)
    TextView tvDes;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.tv_available_money)
    TextView tvAvailableMoney;
    @BindView(R.id.tv_withdraw)
    RoundTextView tvWithdraw;
    @BindView(R.id.gridView)
    GridView gridView;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    @BindView(R.id.rl_info)
    RelativeLayout rlInfo;
    @BindView(R.id.recyclerview_active)
    RecyclerView mRecyclerview;
    @BindView(R.id.tv_agent)
    TextView tvAgent;
    @BindView(R.id.tv_commission_share)
    TextView tvCommissionShare;
    @BindView(R.id.rl_safe)
    RelativeLayout rlSafe;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.tv_active_title)
    TextView tvActiveTitle;
    private MyActiveAdapter mAdapter;
    private List<UserInfo.ActivityListBean.DataBean> mDataList = new ArrayList<>();
    private int mWithDrawStatus = 0;//提现状态  0-未提现，1-正在提现，2-审核通过，3-审核拒绝
    private String phoneNumber = "";

    private List<Integer> images = Arrays.asList(R.mipmap.personal_vote, R.mipmap.personal_invite, R.mipmap.personal_commission,
            R.mipmap.personal_love, R.mipmap.personal_praise);
    private List<String> names = Arrays.asList("投票记录", "我的艺人", "我的收益", "专属礼物记录", "点赞记录");
    private List<String> sizes = Arrays.asList("0票", "0人", "0.00元", "0人", "");
    private List<Class<? extends BaseActivity>> clazzs = Arrays.asList(VoteActivity.class, InviteActivity.class, CommissionActivity.class, LoveActivity.class, StarActivity.class);
    private List<MyGridModel> gridModels;
    private GridAdapter mGridAdapter;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateUI(String event) {
        if (C.EVENT.DISH_FINISH.equals(event) || C.EVENT.UPDATE_USERINFO.equals(event) || C.EVENT.SIGN_SUCCESS.equals(event)) {
            //更新ui
            loadDatas();
        }
    }

    @Override
    protected int layoutId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void bindData() {
        EventBus.getDefault().register(this);
        gridModels = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            MyGridModel gridModel = new MyGridModel();
            gridModel.setImage(images.get(i));
            gridModel.setName(names.get(i));
            gridModel.setSize(sizes.get(i));
            gridModels.add(gridModel);
        }
        mGridAdapter = new GridAdapter(getContext(), gridModels, R.layout.item_mygrid);
        gridView.setAdapter(mGridAdapter);
        loadDatas();
    }

    @Override
    protected void bindListener() {
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                toActivity(clazzs.get(position));
            }
        });
    }

    private void loadDatas() {
        Map<String, String> map = new HashMap<>();
        map.put("page", String.valueOf(1));
        RetrofitManager.ApiFunc(RetrofitManager.mApiService.getMyInfo(map), new SubscriberListener<BaseResponse<UserInfo>>() {
            @Override
            public void onSuccess(BaseResponse<UserInfo> userInfoBaseResponse) {
                UserInfo dataBean = userInfoBaseResponse.data;
                if (dataBean != null) {
                    GlideUtil.displayCircleWithBorder(getContext(), ivAvatar, dataBean.getAvatar(), 2, getResources().getColor(R.color.white));
                    setWithDrawStatus(userInfoBaseResponse.data.getStatus());
                    if (TextUtils.isEmpty(dataBean.getNickname())) {
                        //昵称为空说明未编辑过个人信息
                        tvInfo.setText("未填写");
                    } else {
                        tvInfo.setText("编辑");
                    }
                    phoneNumber = dataBean.getPhone();
                    if (TextUtils.isEmpty(phoneNumber)){
                        tvNumber.setText("未绑定");
                    }else {
                        tvNumber.setText("已绑定手机号");
                    }
                    tvNick.setText(dataBean.getNickname());
                    tvDes.setText(dataBean.getSign());
                    tvTotalMoney.setText(dataBean.getMoney());
                    tvAvailableMoney.setText(dataBean.getMoney_dish());
                    sizes = Arrays.asList(String.valueOf(dataBean.getTicket_all_num()), String.valueOf(dataBean.getConvey_num()),
                            dataBean.getMoney(), String.valueOf(dataBean.getLove_num()), "");
                    for (int i = 0; i < sizes.size(); i++) {
                        MyGridModel model = gridModels.get(i);
                        String suffix = "";
                        if (i == 0) {
                            suffix = "票";
                        } else if (i == 1 || i == 3) {
                            suffix = "人";
                        } else if (i == 2) {
                            suffix = "元";
                        }
                        model.setSize(sizes.get(i) + suffix);
                    }
                    mGridAdapter.notifyDataSetChanged();
                    mDataList = dataBean.getActivityList().getData();
                    initRecycle();
                }
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }

    private void setWithDrawStatus(int status) {
        mWithDrawStatus = status;
        tvWithdraw.setVisibility(View.VISIBLE);
        switch (status) {
            case 1:
                tvWithdraw.setText("提现中");
                tvWithdraw.setTextColor(getResources().getColor(R.color.text_hint));
                tvWithdraw.getDelegate().setStrokeColor(getResources().getColor(R.color.text_hint));
                break;
            case 2:
            default:
                tvWithdraw.setText("申请提现");
                tvWithdraw.setTextColor(getResources().getColor(R.color.yellow_text));
                tvWithdraw.getDelegate().setStrokeColor(getResources().getColor(R.color.yellow_text));
                break;
        }
    }

    private void initRecycle() {
        if (mDataList.size() == 0){
            tvActiveTitle.setVisibility(View.GONE);
        }else {
            tvActiveTitle.setVisibility(View.VISIBLE);
        }
        mAdapter = new MyActiveAdapter(mDataList, getContext());
        mRecyclerview.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerview.setAdapter(mAdapter);
//        mRecyclerview.addItemDecoration(
//                new HorizontalDividerItemDecoration.Builder(getActivity())
//                        .color(ContextCompat.getColor(getActivity(), R.color.divider_line))
//                        .size(DensityUtil.dip2px(getActivity(), 5))
//                        .build());
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                UserInfo.ActivityListBean.DataBean dataBean = (UserInfo.ActivityListBean.DataBean) adapter.getItem(position);
                if (dataBean != null) {
                    ObjectDetailActivity.start(getActivity(), String.valueOf(dataBean.getUid()), String.valueOf(dataBean.getAaid()));
                }
            }
        });
    }

    @OnClick({R.id.iv_set, R.id.tv_withdraw, R.id.rl_info, R.id.rl_safe, R.id.tv_agent, R.id.tv_commission_share})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_set:
                SettingActivity.start(getActivity());
                break;
            case R.id.tv_withdraw:
                if (mWithDrawStatus == 0) {
                    withdraw();
                }
                break;
            case R.id.rl_info:
                PersonDataActivity.start(getActivity());
                break;
            case R.id.rl_safe:
                SafeInfoActivity.start(getActivity(), phoneNumber);
                break;
            case R.id.tv_agent:
                H5Activity.start(getActivity(), H5Activity.AGENT_URL);
                break;
            case R.id.tv_commission_share:
                H5Activity.start(getActivity(), H5Activity.PLAYER_NOTICE_URL);
                break;
        }
    }

    private void withdraw(){
        HttpUtils.ApiFunc(RetrofitManager.mApiService.extract(), new SubscriberListener<BaseResponse<Extract>>() {
            @Override
            public void onSuccess(BaseResponse<Extract> extractBaseResponse) {
                if (extractBaseResponse.data.isIsextract()){
                    startActivity(new Intent(getActivity(), CommissionTypeActivity.class).putExtra("dish_num", tvAvailableMoney.getText()));
                }else {
                    ToastUtil.show("提现时间为5月21日，活动结束方可提现");
                }
            }

            @Override
            public void onFailer(String msg) {
                ToastUtil.show("提现时间为5月21日，活动结束方可提现");
            }

            @Override
            public void onTokenError() {

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        loadDatas();
    }
}
